About 2268 letters

About 11 minutes

#Python's condition variable

A condition variable is a synchronization mechanism used in operating systems and concurrent programming to coordinate communication between threads or processes. It allows a thread to wait when a certain condition is not met and be notified when another thread signals that the condition might have changed.

In Python, you can create a condition variable using the Condition class from the threading module. Use the wait method to wait for a signal, and the notify method to send a notification.

A condition variable includes an internal lock. You can pass a lock as an argument when creating a Condition; if omitted, it will automatically create a reentrant lock. You can acquire and release the lock using the acquire and release methods, or more commonly, use a with statement.

Here’s an example where a consumer thread waits until the variable count reaches 10 before proceeding:

from threading import Thread, Condition count: int = 0 cond = Condition() def consumer(): global count while True: with cond: # Lock to protect count print('consumer') cond.wait() # Atomically release the lock and wait for notification; # re-acquires the lock upon being notified if count == 10: # Check the value of count print(count) break def producer(): global count while True: with cond: # Lock to protect count print('producer') count += 1 # Increment count cond.notify() # Send notification if count == 10: # Terminate when done break t1 = Thread(target=consumer) # Create thread t2 = Thread(target=producer) t1.start() # Start thread t2.start() t1.join() # Wait for thread to finish t2.join()

Created in 5/15/2025

Updated in 5/21/2025